package com.zhang.novel.controller;

import com.zhang.novel.core.bean.UserDetails;
import com.zhang.novel.core.utils.CookieUtil;
import com.zhang.novel.core.utils.JwtTokenUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;

public class BaseController {
    protected JwtTokenUtil jwtTokenUtil;

    @Autowired
    public void setJwtTokenUtil(JwtTokenUtil jwtTokenUtil) {
        this.jwtTokenUtil = jwtTokenUtil;
    }

    /**
     * 获取token
     * @param request
     * @return
     */
    protected String getToken(HttpServletRequest request) {
        // 从cookie中获取token
        String token = CookieUtil.getCookie(request,"Authorization");
        if(null != token){
            return token;
        }
        return request.getHeader("Authorization");
    }

    protected UserDetails getUserDetails(HttpServletRequest request) {
        // 获取token
        String token = getToken(request);
        // 判断用户是否登录，是则从token中获取用户信息
        if (StringUtils.isBlank(token)) {
            return null;
        } else {
            return jwtTokenUtil.getUserDetailsFormToken(token);
        }
    }
}
